<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';
	require '../include/paging.inc.php';
	
	
	$sql_lang = 'SELECT lang_id,Name,code FROM language WHERE published ';	
		
	if (!isset($_POST['is_submitted'])) {
		$_POST['is_submitted'] = '';
	}
	if (!isset($error_message)) {
		$error_message = '';
	}	
	$product_id = $_GET["product_id"];

	if($_POST["redirect"] || $_SESSION['redirect'] ){
		if($_POST["redirect"]) $redirect = $_POST["redirect"];
		if($_SESSION['redirect']){ 
		$redirect = $_SESSION['redirect'];
		unset($_SESSION['redirect']);
		}
	}else{
		   $redirect = $_SERVER['HTTP_REFERER'];	
		 }
		
		if ($_POST['is_submitted']) {
			$error_message = '';
			$redirect = $_POST["redirect"];
		
		$result_lang = query($sql_lang);
		while ($row_lang = mysql_fetch_object($result_lang)) {
		
			if (!$_POST['title'][$row_lang->lang_id])  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
			
			
			
		
		}
		
		
		require "../include/image_allowed_type.inc.php";
		
		if ($_FILES['cover']['name']){
		
		if(!array_search($_FILES['image']['type'], $allowed_types) && $_FILES['image']['name']) $error_message .= 'Форматът на  снимката за корица не е позволен<br/>';
		
		/*$size = getimagesize($_FILES['cover']['tmp_name']);
		if ($size[0]!== BIG_WIDTH) $error_message .= 'Широчината на снимката за корица не е точно '.BIG_WIDTH.' пиксела!<br/>';
		if ($size[1]!== BIG_HEIGHT) $error_message .= 'Височината на снимката за корица не е точно '.BIG_HEIGHT.' пиксела!<br/>';*/
		}
		
		
		if(!$error_message) {
			
			//Update DB
			$sql = "UPDATE products SET
					 
					
					published = '".intval($_POST['published'])."',
					video = '".escape($_POST['video'])."',
					coor = '".escape($_POST['coor'])."'
					 
					 WHERE
					 product_id = '$product_id'
					";
			query($sql);
	
			$result_lang = query($sql_lang);
			$lang_num = 0;
			while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$sql = "UPDATE product_description SET
						 title = 		 '".escape($_POST['title'][$row_lang->lang_id])."',
						 meta_description = 		 '".escape($_POST['meta_description'][$row_lang->lang_id])."', 
						 description = '".escape($_POST['description'][$row_lang->lang_id])."'
					WHERE
						 product_id = '".$product_id."'
						 AND
						 lang_id = '".$row_lang->lang_id."'
					  ";
					
				query($sql);
			
			
				$lang_num++;
			}
			if($_FILES['cover']['tmp_name']){
				
				$upload_path = "../product_images/";
				if (is_uploaded_file($_FILES['cover']['tmp_name'])) {
							
							$tmp_file = $_FILES['cover']['tmp_name'];
							$exp = explode('.',$_FILES['cover']['name']);
							$img_type = strtolower(end($exp));
							$new_name = "image".$product_id.".".$img_type;
							
							
							
							if(!copy($tmp_file, $upload_path.'big/'.$new_name)) {
				
								$_SESSION['message'] .= 'Грешка при качване на снимка. ';
							}
			
							
							
							include '../include/image_man.php';
							$imn = new ImageManipulator;
							$imn -> decider($img_type,$tmp_file);
							
							if(copy($tmp_file.'_image', $upload_path.'medium/'.$new_name) && copy($tmp_file.'_thumb', $upload_path.'covers/'.$new_name)) {
							
								$sql = "UPDATE products SET
											cover = '$new_name'
										WHERE product_id = '$product_id'";
								query($sql);
								
							} else{
								$_SESSION['message'] .= 'Грешка при качване на снимка. ';
							}			
							
					}
			}
			
			
			
			if($_POST['category_id'])
			{
				
				$sql = "DELETE FROM 
				  product_to_category
				WHERE
				  product_id = '".$product_id."'
				   
				   
				 ";
				query($sql);
				
				$category_id = $_POST['category_id'];
			  
				foreach ($category_id as $key => $value) {
				
					$sql = 'INSERT INTO  product_to_category
								  (product_id,category_id)
								VALUES
								  ('.$product_id.','.intval($value).')
								  ';
					query($sql);
				
				}
			}
			
			
			$_SESSION['message'] .= 'Продукта е редактиран успешно!';
			
			if($_POST["redirectForm"]){
			   redirect($_POST["redirectForm"]);
			}else{
				$_SESSION['redirect'] = $redirect;
			   redirect(HTML_BASE_ADMIN.'product_edit.php?product_id='.$product_id);
			   
			   
			}
		}
		


	
	}else{
		$sql = "SELECT 
				creation_time,
				coor,
				cover,
				video,
				published
			FROM
				products
			WHERE
				product_id ='".$product_id."'
			
			";
		$result_cat = query($sql);
		$row_cat = mysql_fetch_object($result_cat);
		$_POST['creation_datetime'] =  $row_cat->creation_time;
		$_POST['published'] =  $row_cat->published;
		$_POST['coor'] =  $row_cat->coor;
		$_POST['cover'] =  $row_cat->cover;
		$_POST['video'] =  $row_cat->video;
		if (!$row_cat) redirect("products.php");
		
	}
	
	
	if ($_POST['is_uploud']) {
    $error_message = '';

   
    if (!$_FILES['image']['name']) $error_message .= 'Не е избрана снимка!<br/>';
	if(!$error_message) {
		
		
		
		
		
		
		if (is_uploaded_file($_FILES['image']['tmp_name'])) {
			$upload_path = "../product_images/gallery/";
			
				
			$tmp_file = $_FILES['image']['tmp_name'];
			$exp = explode('.',$_FILES['image']['name']);
			$img_type = strtolower(end($exp));
			
			$sql = "SELECT MAX(order_number)+1 AS order_number FROM product_gallery WHERE product_id = '".$product_id."'";
			$row_number = mysql_fetch_assoc(query($sql));
		
			//Въвеждаме в базата данни
			$sql = "INSERT INTO product_gallery
					  (product_id, order_number)
					VALUES
					  ('".$product_id."', '".$row_number['order_number']."')
					  ";
			query($sql);
			$image_id = mysql_insert_id();
			
			
			if(!copy($tmp_file, $upload_path.'big_image'.$image_id.'.'.$img_type)) {
				
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
			}
			
			
			include '../include/image_man.php';
		    $imn = new ImageManipulator;
			$imn -> decider($img_type,$tmp_file);
			///////////////////////////////////////////////
			
			
			
			$result_lang = query($sql_lang);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$em = $row_lang->lang_id;
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				$sql = "INSERT INTO product_gallery_description
				  (image_id, lang_id, description)
				VALUES
				  ('".$image_id."','".$em."','".escape($_POST['img_description'][$em])."')";
				 
				query($sql);
		}
			
			///////////////////////////////////////////////
			
			
			if(copy($tmp_file.'_image', $upload_path.'image_'.$image_id.'.'.$img_type) && copy($tmp_file.'_thumb', $upload_path.'th_image_'.$image_id.'.'.$img_type))
			{
				$sql = 'UPDATE product_gallery
						SET
							file = \'image_'.$image_id.'.'.$img_type.'\'
						WHERE
							id = '.$image_id.'
						  ';
				query($sql);
				
			} else {
				
				$sql = 'DELETE FROM 
						   product_gallery
						WHERE
						   id = '.$image_id.'
						 ';
				query($sql);
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
				
			}	
			redirect("product_edit.php?product_id=".$_REQUEST["product_id"]."#gallery");
		}
		
		
	}
	
}

	
	head_admin("Редактиране на продукт");
?>
<link rel="stylesheet" type="text/css" href="<?=HTML_BASE_ADMIN?>fancybox/jquery.fancybox-1.3.1.css" media="screen" />
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>fancybox/jquery.fancybox-1.3.1.pack.js"></script> 
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "bg", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,
});
</script>
		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Редактиране на продукт</h3>

     
     
             
            
<form id="page_product_form_id" action="<?=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
			<input type="hidden" name="redirect" value="<?=$redirect?>" />
             <input id="redirectForm" type="hidden" name="redirectForm" value="" />
          
<?php 
			
		
			$result = query($sql_lang);
			
			$i=0;
			
			?>
				
 
			
	<div id="tabs">
        
        	<ul id="tabs-ui">
           
			</ul>
			
			
			<?php
			$tabs="";
			$result_lang = query($sql_lang);
			while ($row_lang = mysql_fetch_object($result)) {
					
				  $tabs.=' <li><a href="'.$_SERVER['PHP_SELF'].'?product_id='.$product_id.'#tabs-'.$row_lang->lang_id.'">'.$row_lang->Name.'</a></li>';

					
			if (!$_POST['is_submitted']) {
				
				
					$sql_d = "SELECT *	FROM product_description
					WHERE
						product_id = '".$product_id."'
						AND 
						lang_id = '".$row_lang->lang_id."'
					";
					$result_d = query($sql_d);
					$row_d = mysql_fetch_object($result_d);
					
					$_POST['title'][$row_lang->lang_id] =  $row_d->title;
					$_POST['description'][$row_lang->lang_id] =  $row_d->description;
					$_POST['meta_description'][$row_lang->lang_id] =  $row_d->meta_description;
					
					
					$sql_s = "SELECT sef_url	FROM sef_url
					WHERE
						tamplate = 'product'
						AND
						query = '".$product_id."'
						AND 
						lang_id = '".$row_lang->lang_id."'
					";
					$result_s = query($sql_s);
					$row_s = mysql_fetch_object($result_s);
					$_POST['sef_url'][$row_lang->lang_id] = $row_s->sef_url;
					
			}
			
			$sef_img = $_POST['sef_url'][$row_lang->lang_id];
								  
			?>
            	
		
              
            <div id="tabs-<?=$row_lang->lang_id?>">
             <dl class="clearfix">
                <h3>Данни на  <?=$row_lang->Name?></h3>
                
                
 Линк за фейсбук: <a style="color:#09F; font-size:9px;" id="fb" href="https://www.facebook.com/ApivitaBulgaria/app_285763294952177?app_data=<?=base64_encode($_POST['sef_url'][$row_lang->lang_id])?>" target="_blank">https://www.facebook.com/ApivitaBulgaria/app_285763294952177?app_data=<?=base64_encode($_POST['sef_url'][$row_lang->lang_id])?></a>
        
        
        
        </dt>	
                
                
                <dt><label class="required">Заглавие:</label></dt>
                <dd><input class="inputbox w500"  name="title[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['title'][$row_lang->lang_id]?>" ></dd>
                <dt><label >Подзаглавие</label></dt>
                <dd><textarea id="title_<?=$row_lang->lang_id?>" class="inputbox w500" name="meta_description[<?=$row_lang->lang_id?>]" rows="3" maxlength="110"><?=$_POST['meta_description'][$row_lang->lang_id]?></textarea></dd>
                <dt><label>Описание:</label></dt>
                <dd><textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description[<?=$row_lang->lang_id?>]" rows="16">
				
				<?php 
				if ($_POST['description'][$row_lang->lang_id]) {
					echo sth($_POST['description'][$row_lang->lang_id]);
				} else {
					echo '<div id="product-quantity">250 ml</div><p>&nbsp;</p>';
				}
				?>
                
                </textarea></dd>
                
                
		    </dl>
           
                    
           </div>
                        
            
		 <?php
				
			}
			
			
	  	  ?>
          
           </div>
			<dl class="clearfix" >
           
            
            <div style="width:40%; float:left;">
                <dt >
                    <label class="required">Корица на проекта (<?=BIG_WIDTH?> на <?=BIG_HEIGHT?> px)
                    </label>
                </dt>
                <dd>
                    <input class="inputbox w250" name="cover" type="file" accept="image/*" />
                </dd>
            	<img width="<?=THUMB_WIDTH?>" src="../product_images/covers/<?=$_POST['cover']?>"/>
            	
                
            </div>
            <div style="width:60%; float:left;">   
                <dt>
      			<h3>Категории</h3>
    		</dt>
    		<dd>
				<ul class="type-box">
				<?php
				$_SESSION['i'] = 1;
				function getCategory($parent,$parent_id){         
                    $sql_c = "SELECT
                    c.category_id,
                    d.Name
                    
                FROM
                    category AS c,
                    category_description AS d
                WHERE
                
                    c.category_id = d.category_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
					
					AND parent_id = '".$parent_id."'
                    
                    ORDER BY c.order_number 
                    
                  ";
                	
                    $result_c = query($sql_c);
                    	
					
					
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="category_id[<?=$_SESSION['i']?>]" type="checkbox" value="<?=$row->category_id?>" 
                           
                                        <?php
								$sql_ch = "SELECT category_id FROM product_to_category WHERE product_id = '".intval($_GET['product_id'])."'  AND category_id = '".$row->category_id."' ";
								
								if ($c_cid = mysql_fetch_object(query($sql_ch))) echo "checked=\"checked\"";
								
                			?> />
                            
                            
                          	<?php 
							
							if($parent){ 
							echo $parent.' > '.sth($row->Name);
							 } else{ 
							 echo sth($row->Name) ;
							 }?>
                          </label>
                        </li>
        			<?php $_SESSION['i']++;
					
					
						getCategory($parent.' > '.sth($row->Name),$row->category_id);
					} 
					
				} 
				getCategory('',0);
				?>
				</ul>
			</dd>
             </div>       
                    
                    
                    <dd ><input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
				<label>Публикуван</label></dd>
               </dl>
           
              
                	
			</form>    
            
            
        <script>
			  
			  $(document).ready(function(e) {
				   $("#tabs-ui").html('<?=$tabs?>');
						
				   $( "#tabs" ).tabs();
			  
			  });		
					
  		</script>
        
        </dl>
        
        <dl>
        
       
       
       
         <h3>Снимки  </h3>
			
			
            
            <table id="listing" width="100%" cellpadding="0" cellspacing="0">
			<thead>
				<tr>
               
					<td>Снимка</td>
                    
                    <?php
					
					$result_l = query($sql_lang);
					while ($row_l = mysql_fetch_object($result_l)) {
                    echo '<td>Описание на '.$row_l->Name.'</td>';
					
					}
					?>
					<td>Подреба</td>
                    <td>Действия</td>
				</tr>
			</thead>
			<tbody>
		<?php
		# Първоначално зареждане
		$lang = '1';
	
		$sql = "SELECT
					id,
					file,
					order_number
					
				  FROM
					product_gallery
				WHERE product_id = '".$product_id."'
				 
				  
					";
		//$result = query($sql);
		if (!isset($_GET['sort'])) $_GET['sort'] = 1;
		if (!isset($_GET['sortBy'])) $_GET['sortBy'] = 3;
		//echo $paging->count();
		$paging = new Paging($sql, $_GET['sortBy'], $_GET['sort'], array(3=>"Подредба"), 150);
			$result = $paging->query();
			$i=1;
            while ($row = mysql_fetch_object($result)) {				  
        ?>
            <tr class="<?=(($i%2)?"none":"zebra")?>">
            
              
              <td><a href="<?=HTML_BASE?>product_images/gallery/<?=$row->file?>"  rel="gallery">
			  <img src="<?=HTML_BASE?>product_images/gallery/th_<?=$row->file?>" height="100"/></a></td>
              <?php
			  $sql_d = "SELECT lang_id,description
					FROM product_gallery_description
					WHERE image_id = '".$row->id."'
					";
              $result_d = query($sql_d);
					while ($row_d = mysql_fetch_object($result_d)) {
						
						?>
                    <td class="desc_<?=$row->id?>"><input class="inputbox w250"   value="<?=$row_d->description?>" /></td>
                    
              <?php
					
					}
              ?>
              
              <td class="sort">
              
              
							
						
              
              
              
							<?php if ($i != 1) { ?>
							<a name="Up" class="sorting_up" title="Нагоре" href="gallery_direction.php?image_id=<?=$row->id?>&product_id=<?=$product_id?>&direction=1"></a>
							<?php } ?>							
							<?php if ($i != ($paging->count())) { ?>
							<a name="Down" class="sorting_down" title="Надолу" href="gallery_direction.php?image_id=<?=$row->id?>&product_id=<?=$product_id?>&direction=-1"></a>
							<?php } ?>
							&nbsp;<!--ie6 bug-->
			</td>
              
              <td class="icons">
              
              
              
              
              <a onClick="saveDescription('<?=$row->id?>'); return false;" class="update" title="Обнови">Обнови</a>
              
              <a onClick="if (window.confirm('Сигурен ли си, че искаш да изтриеш тази снимка?')) { document.location='image_del.php?image_id=<?=$row->id?>&product_id=<?=$product_id?>'; return false; }" class="delete" title="Изтрий">Изтрий</a>
              </td>
              
              
            </tr>
         <?php 
		 $i++;
		 
		 } ?>				
			</tbody>
		</table>
        <a name="gallery"></a>
        <div class="pagingwrap"><div class="paging">
			<?=$paging->display()?>
		</div></div>
        
        
        <?php if($i < 6){?>
        <form id="gallery_form" action="<?=$_SERVER['PHP_SELF']?>?<?=$_SERVER['QUERY_STRING']?>#gallery" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_uploud" value="1" />
            
           
            
			<dl class="clearfix">
            
            <h3>Нова снимка</h3>
            		
            <input class="inputbox" name="image" type="file" /><br />
            
            
            <div id="tabs-img">
            <ul id="ui-img"></ul>
            
           <?php
		   
			$result = query($sql_lang);
			
			$i=0;
			$tabs = '';
			while ($row_lang = mysql_fetch_object($result)) {
		
				$em = $row_lang->lang_id;
				
				$tabs .=' <li><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'#tabs-img-'.$em.'">Описание на '.$row_lang->Name.'</a></li>';
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				?>
                <div id="tabs-img-<?=$em?>">
            
            <dd><input class="inputbox w500" name="img_description[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['img_description'][$row_lang->lang_id]?>" ></dd>
            	</div>
            <?php }?>
            </div>
            
            
            <a class="button" onclick="unsaved = false; $('#gallery_form').submit(); return false;">Качване</a>
            
            </dl>
			

            
			

            
            
            
            </form>
            
              <script>
				$(document).ready(function() {
				
					// Tabs
					$("#ui-img").html('<?=$tabs?>');
					$( "#tabs-img" ).tabs();	
					
				});
			</script>
        <?php }?>
        
        <script type="text/javascript">
		function saveDescription(image)
		{
			var decription = new Array(image);
			$('.desc_'+image+' input').each(function() {
                decription.push($(this).val());
				
            });
			
			var jsonString = JSON.stringify(decription);
			
			$.ajax({
					type: 'POST',
					url: 'album_ajax_desc.php',
					data: {data : jsonString} ,
					success: function(msg){
						
						alert(msg);
						
						
						
					},
					error: function(msg){
						alert('Err:'+ msg)
					}
				});
			
		}
		
		
	$(document).ready(function() {
		
		
		
		
		
		$("a[rel=gallery]").fancybox({
			'titlePosition' 	: 'over'
		});
	});
</script>
            
            
<?php
	controls($redirect, "#page_product_form_id");
	foot_admin(); 
?>